import { createRouter, createWebHashHistory, RouteRecordRaw, useLink } from "vue-router";

const BasicLayout = () => import("/@/layout/BasicLayout.vue");
const UserLayout = () => import("/@/layout/UserLayout.vue");
const GisLayout = () => import("/@/layout/GisLayout.vue");

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: BasicLayout,
    children: [
      {
        path: "/user",
        name: "user",
        component: UserLayout,
        children: [
          {
            path: ":otherString*",
            redirect: "/user/login",
          },
          {
            path: "login",
            name: "login",
            component: () => import("/@/pages/user/login.vue"),
          },
          {
            path: "register",
            name: "register",
            component: () => import("/@/pages/user/register.vue"),
          },
          {
            path: "password",
            name: "password",
            component: () => import("/@/pages/user/password.vue"),
          },
          {
            path: ":userId(\\d+)",
            name: "userinfo",
            component: () => import("/@/pages/user/info.vue"),
            props: (route) => ({ userId: route.params.userId }),
          },
        ],
      },
      {
        path: 'home',
        name: 'home',
        component: GisLayout,
        children: [
          {
            path: 'dashboard',
            name: 'dashboard',
            component: () => import('/@/pages/gis/dashboard/index.vue')
          },
          {
            path: 'static',
            name: 'static',
            component: () => import('/@/pages/gis/static/index.vue')
          }
        ],
      }
    ],
  },
];

const router = createRouter({
  // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
  history: createWebHashHistory(),
  routes, // short for `routes: routes`
});

router.beforeEach(async (to, from, next) => {
  // console.log({ to, from });
  const isAuthorization = sessionStorage.getItem("isAuthorization");
  // console.log(
  //   router,
  //   to,
  //   to.path,
  //   router.hasRoute(to.name),
  //   router.hasRoute(to.name)
  // );
  let rootPath = "";
  if (isAuthorization) {
    rootPath = "/user/login";
  } else {
    rootPath = "/home";
  }
  if (to.fullPath === "/" || !router.hasRoute(to.name)) {
    next(rootPath);
  } else {
    next();
  }
});

export default router;
